/*
 * File     : LastError.java
 * Created  : 18 Dec 2011
 *
 * Copyright © 2011 Matthew Wilson (mj. {my-surname} .uk {at} gmail.com)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.googlecode.dni.internal.call;

import java.util.logging.Level;

import com.googlecode.dni.internal.DniInternal;
import com.googlecode.dni.library.SystemException;
import com.googlecode.dni.type.Pointer;

/**
 * <p>
 *  Provides a mechanism for recording the last error value.
 * </p>
 *
 * @author Matthew Wilson
 */
public final class LastError
{

    private static final ThreadLocal< Slot > LAST_ERROR_SLOT = new ThreadLocal< Slot >()
    {
        @Override
        protected Slot initialValue()
        {
            return new Slot();
        }
    };

    /**
     * @return the last error for this thread
     */
    public static int getLastError()
    {
        return DniInternal.MEMORY_ACCESSOR.getInt( getLastErrorSlotAddress64() );
    }

    /**
     * @param error
     *           the last error for this thread
     */
    public static void setLastError( final int error )
    {
        DniInternal.MEMORY_ACCESSOR.putInt( getLastErrorSlotAddress64(), error );
    }

    /**
     * @return the address of the last error slot for the calling thread
     */
    public static long getLastErrorSlotAddress64()
    {
        return LAST_ERROR_SLOT.get().address;
    }

    /**
     * @return the address of the last error slot for the calling thread
     */
    public static int getLastErrorSlotAddress32()
    {
        return (int) LAST_ERROR_SLOT.get().address;
    }

    /**
     * Throws if the last error is non-zero.
     *
     * @throws SystemException
     *             on non-zero last error value
     */
    public static void throwIfNonZero()
    {
        int error = getLastError();
        if ( error != 0 )
        {
            throw new SystemException( error );
        }
    }

    private static final class Slot
    {
        private final long address;

        Slot()
        {
            this.address = DniInternal.ALLOCATOR.allocate( 64 ).address();
            DniInternal.LOGGER.fine( "Allocating LastError slot for thread: 0x" + Long.toHexString( this.address ) );
        }

        @Override
        protected void finalize()
        {
            try
            {
                DniInternal.LOGGER.fine( "Freeing LastError slot for thread: 0x" + Long.toHexString( this.address ) );
                DniInternal.ALLOCATOR.free( Pointer.fromAddress( this.address ) );
            }
            catch ( Throwable throwable )
            {
                DniInternal.LOGGER.log( Level.SEVERE, "Failed to free slot for LastError", throwable );
            }
        }
    }

}
